/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package autentifikacia;

import hlavneMenu.HlavneMenu;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import strukturaSviatky.Sviatky;

/**
 *
 * @author akinorev
 */
public class PrihlasovaciFormular extends javax.swing.JFrame {

    /*
     * Creates new form PrihlasovaciFormular
     */
    /*private variables*/
    private Connection con = null;
    private String url = "jdbc:mysql://kempelen.ii.fmph.uniba.sk:3306/";
    private String db = "vratnica";
    private String driver = "com.mysql.jdbc.Driver";
    private String user = "vratnica";
    private String pass = "MonikaVeronika";

    public PrihlasovaciFormular() {
        initComponents();

        //centralizovanie okna
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int X = (screen.width / 2) - (this.getWidth() / 2); // Center horizontally.
        int Y = (screen.height / 2) - (this.getHeight() / 2); // Center vertically.
        this.setLocation(X, Y);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    private boolean porovnajLogin(String log, String pas) throws SQLException, ParseException {
        try {
            //pripojenie do databazy
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url + db, user, pass);
        } catch (Exception e) {
            Logger.getLogger(Sviatky.class.getName()).log(Level.SEVERE, null, e);
        }
        Statement st = con.createStatement();
        /*overí podla databazy v tabulke admin_table login a heslo, ak sa obe zhoduju, vrati true */
        //porovnanie loginu a hesla
        ResultSet res = st.executeQuery("SELECT * FROM admin_table");
        while (res.next()) {
            if (log.equals(res.getString("login")) && pas.equals(res.getString("heslo"))) {
                return true;
            }
        }
        return false;
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        nadpisLabel = new javax.swing.JLabel();
        menoLabel = new javax.swing.JLabel();
        hesloLabel = new javax.swing.JLabel();
        menoTextField = new javax.swing.JTextField();
        hesloTextField = new javax.swing.JPasswordField();
        submitButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Prihlasovací formulár");


        nadpisLabel.setFont(new java.awt.Font("Arial", 1, 20)); // NOI18N
        nadpisLabel.setText("Prihlasovací formulár");

        menoLabel.setText("Prihlasovacie meno:");

        hesloLabel.setText("Heslo:");

        submitButton.setText("Prihlásiť");
        submitButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addGap(156, 156, 156)
                .addComponent(submitButton))
                .addGroup(layout.createSequentialGroup()
                .addGap(83, 83, 83)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(hesloTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(menoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(hesloLabel)
                .addComponent(menoLabel))
                .addGap(98, 98, 98)))
                .addComponent(nadpisLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(99, Short.MAX_VALUE)));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(nadpisLabel)
                .addGap(28, 28, 28)
                .addComponent(menoLabel)
                .addGap(11, 11, 11)
                .addComponent(menoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(hesloLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(hesloTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addComponent(submitButton)
                .addContainerGap(32, Short.MAX_VALUE)));
        getRootPane().setDefaultButton(submitButton);
        pack();
    }// </editor-fold>                        

    private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
        String name;
        String pssword;
        try {
            name = this.menoTextField.getText();
            pssword = this.hesloTextField.getText();
            if (name.length() < 3) {
                JOptionPane.showMessageDialog(this, "Prihlasovacie meno je príliš krátke!", "Chyba", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (pssword.length() < 5) {
                JOptionPane.showMessageDialog(this, "Heslo musí obsahovať minimálne 5 znakov!", "Chyba", JOptionPane.ERROR_MESSAGE);
                return;
            }

            pssword = MD5coder.MD5(pssword);
            /*Nacitali sa prihlasovacie udaj z formulara, zakodovali sa do MD5*/
            if (porovnajLogin(name, pssword)) {
                HlavneMenu hm = new HlavneMenu();
                hm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                hm.setVisible(true);
                dispose();
            }
            /*skontrolovali sa podla udajov v databaze, 
             * predbezne sa zobrazi len informacia, ze sa zhoduju*/
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Zlé prihlasovacie údaje!", "Chyba", JOptionPane.ERROR_MESSAGE);
            System.out.println(e.getMessage());
        }
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PrihlasovaciFormular.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PrihlasovaciFormular.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PrihlasovaciFormular.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PrihlasovaciFormular.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new PrihlasovaciFormular().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JLabel hesloLabel;
    private javax.swing.JTextField hesloTextField;
    private javax.swing.JLabel menoLabel;
    private javax.swing.JTextField menoTextField;
    private javax.swing.JLabel nadpisLabel;
    private javax.swing.JButton submitButton;
    // End of variables declaration                   
}
